package com.compass.doctor.ui.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_SETTLING
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnDrugSelectClick
import com.compass.doctor.databinding.ActivityPharmacyBinding
import com.compass.doctor.ui.home.adapter.DrugTabAdapter
import com.compass.doctor.ui.home.fragment.DrugFragment
import com.compass.doctor.ui.home.viewmodel.DrugViewModel
import com.compass.framework.adapter.ViewPage2FragmentAdapter
import com.compass.framework.constant.KEY_INDEX
import com.compass.framework.ext.toJson
import com.compass.framework.model.Drug
import com.compass.framework.model.DrugTabItem
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * Description： 药房
 * Date:2024/2/19 16:09
 */
class PharmacyActivity :BaseVBActivity<ActivityPharmacyBinding>(), OnRefreshListener {


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, PharmacyActivity::class.java)
            context.startActivity(intent)
        }
    }

    private var allDrug: MutableList<DrugTabItem> = ArrayList()
    private var isSearch: Boolean = false//是否是搜索
    //当前选中的position
    private var mCurrentSelectPosition = 0
    private var fragments: ArrayList<Fragment> = ArrayList()
    private lateinit var mTabAdapter: DrugTabAdapter
    private var mViewPagerAdapter: ViewPage2FragmentAdapter? = null
    private val drugViewModel: DrugViewModel by viewModels()
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.edtDrugName.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val keyWord = mBinding.edtDrugName.text.toString()
                if (isSearch) {
                    showLoading()
                    drugViewModel.getPharmacyInfo(keyWord)
                } else {
                    showToast("请输入搜索条件")
                }
            }
            false
        }
        mBinding.edtDrugName.addTextChangedListener {
            it?.let {
                isSearch = it.isNotEmpty()
                if (it.isEmpty())  setViewData(allDrug)
            }
        }
        mBinding.refreshLayout.apply {
            setEnableRefresh(false)
            setEnableLoadMore(false)
            setOnRefreshListener(this@PharmacyActivity)

        }
        initTabRecyclerView()
        initViewPager2()


    }
    private fun initTabRecyclerView() {
        mTabAdapter = DrugTabAdapter()
        mBinding.tabRecyclerView.apply {
            layoutManager = LinearLayoutManager(this@PharmacyActivity)
            adapter = mTabAdapter
        }
        mTabAdapter.onItemClickListener = { view: View, position: Int ->
            updateTabItem(position)
            mBinding.viewPager2.setCurrentItem(position, false)
        }
    }

    private fun initViewPager2() {
        mViewPagerAdapter = ViewPage2FragmentAdapter(supportFragmentManager, lifecycle, fragments)
        mBinding.viewPager2.apply {
            offscreenPageLimit = ViewPager2.SCROLL_STATE_SETTLING
            orientation = ViewPager2.ORIENTATION_VERTICAL
            registerOnPageChangeCallback(viewPager2Callback)
            adapter = mViewPagerAdapter
        }
    }


    override fun initData() {
        showLoading()
        drugViewModel.getPharmacyInfo()
        drugViewModel.drugTabLiveData.observe(this) { drugs ->
            dismissLoading()
            mBinding.refreshLayout.finishRefresh()
            drugs?.let {
                setViewData(it)
            }

        }
    }

    private var onDrugItemClick = object : OnDrugSelectClick {
        override fun onDrugSelectCallBack(drug: Drug) {

        }
    }

    private fun setViewData(drugs: MutableList<DrugTabItem>) {
        //默认第一条选中
        drugs.firstOrNull()?.isSelected = true
        if (!isSearch) allDrug = drugs //不是搜索的情况下存存储全部数据
        mTabAdapter.setData(drugs)
        mTabAdapter.notifyDataSetChanged()
        drugs.forEachIndexed { index, item ->
            if (fragments.size < drugs.size) {
                var fragment = DrugFragment.newInstance(item.drugs?.toJson(true) ?: "", 1)
                fragments.add(index,fragment)
                fragment.setDrugItemClick(onDrugItemClick)
            } else {
                var fragment = fragments[index] as DrugFragment
                if(fragment.isAdded){
                    fragment.setList(item.drugs)
                }
            }
        }
        mViewPagerAdapter?.notifyItemRangeChanged(0, drugs.size)
    }



    /**
     * 更新Tab状态
     * @param position 选择的item
     */
    private fun updateTabItem(position: Int) {
        mTabAdapter.setCurrentPosition(position)

        if (mCurrentSelectPosition != position) {
            //更新上一条item
            val selectedItem = mTabAdapter.getItem(mCurrentSelectPosition)
            selectedItem?.let { it.isSelected = false }
            //更新当前item
            val newItem = mTabAdapter.getItem(position)
            newItem?.let { it.isSelected = true }

            mCurrentSelectPosition = position
            mTabAdapter.notifyDataSetChanged()
            mBinding.tabRecyclerView.smoothScrollToPosition(position)
        }
    }

    /**
     * VIewPager2选择回调
     */
    private val viewPager2Callback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            updateTabItem(position)
        }
    }

    override fun onDestroy() {
        mBinding.viewPager2.unregisterOnPageChangeCallback(viewPager2Callback)
        super.onDestroy()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        drugViewModel.getPharmacyInfo()
    }


}